import { useQuery } from "@apollo/react-hooks";
import gql from "graphql-tag";

import { usePageContext } from "../hooks/useContext";

export const QUERY = gql`
  query QuerySysRoles($query: SysRoleQueryInput!) {
    querySysRoles(query: $query) {
      count
      items {
        id
        name
        description
        dateCreated
        dateUpdated
        authorities {
          id
          description
        }
      }
    }
  }
`;

export const useTable = () => {
  const {
    state: { query },
    dispatch
  } = usePageContext();

  const { data, loading, error, refetch } = useQuery(QUERY, {
    variables: {
      query
    }
  });

  const handleChange = async (pagination, filters, sorter) => {
    dispatch({
      type: "QUERY_CHANGE",
      payload: {
        pagination: {
          current: pagination.current,
          pageSize: pagination.pageSize
        },
        query: {
          skip: (pagination.current - 1) * pagination.pageSize,
          first: pagination.pageSize,
          sortName: sorter.field,
          sortOrder: sorter.order
        }
      }
    });
    refetch();
  };

  return {
    total: (data && data.querySysRoles && data.querySysRoles.count) || 0,
    items: (data && data.querySysRoles && data.querySysRoles.items) || [],
    loading,
    error,
    handleChange
  };
};
